#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;

using octalforty.Componento.ComponentModel.Impl;
using octalforty.Componento.ComponentModel.Tracing;
using octalforty.Componento.Shared.SemanticModel;
using octalforty.Wizardby.Core.Db;

namespace octalforty.Componento.ComponentModel.Installation
{
    [Export(typeof(IInstalledComponentRegistryService))]
    public class InstalledComponentRegistryService : SQLiteServiceBase, IInstalledComponentRegistryService
    {
        #region Public Properties
        public ITrace Trace
        { get; set; }

        public ITraceManagerService TraceManager
        { get; set; }
        #endregion

        [ImportingConstructor()]
        public InstalledComponentRegistryService(ITraceManagerService traceManager)
        {
            TraceManager = traceManager;
            Trace = TraceManager.GetTrace(GetType().Name);
        }

        #region SQLiteServiceBase Members
        protected override string DatabaseFileName
        {
            get { return "componento.db"; }
        }

        protected override string DatabaseMigrationDefinitionResourceName
        {
            get { return "octalforty.Componento.ComponentModel.Installation.Componento.mdl"; }
        }
        #endregion

        #region IInstalledComponentRegistryService Members
        /// <summary>
        /// Returns an array of <see cref="ComponentReference"/> objects which represent
        /// installed components.
        /// </summary>
        public ComponentReference[] InstalledComponents
        {
            get 
            {
                return new List<ComponentReference>(
                    ExecuteDataReader("select * from Component order by Name;", GetComponentReferenceMapper())).
                    ToArray();
            }
        }

        /// <summary>
        /// Registers component <paramref name="componentReference"/>.
        /// </summary>
        /// <param name="componentReference"></param>
        public void RegisterComponent(ComponentReference componentReference)
        {
            try
            {
                #region Tracing
                Trace.Verbose( "Registering Component '{0}' {1} '{2}'", 
                    componentReference.Name, componentReference.Version, componentReference.Uri);
                #endregion

                DbUtil.ExecuteInTransaction(DbPlatform, ConnectionString,
                    delegate(IDbTransaction transaction)
                        {
                            DbManager.Execute(DbPlatform.ProviderFactory, transaction,
                                "insert into Component (Name, Version, Uri) values (:name, :version, :uri);",
                                new string[] { "name", "version", "uri" },
                                new object[] { componentReference.Name, componentReference.Version.ToString(), componentReference.Uri.ToString() });
                        });

                #region Tracing
                Trace.Verbose( "Registered Component '{0}' {1} '{2}'", 
                    componentReference.Name, componentReference.Version, componentReference.Uri);
                #endregion
            } // try

            catch(SQLiteException e)
            {
                if(e.ErrorCode == SQLiteErrorCode.Constraint)
                {
                    throw new ComponentRegistrationException();
                } // if

                throw;
            } // catch
        }

        /// <summary>
        /// Registers names of components <paramref name="dependencies"/> as dependencies of
        /// component <paramref name="componentName"/>.
        /// </summary>
        /// <param name="componentName">The name of the component.</param>
        /// <param name="dependencies">Names of components <paramref name="componentName"/> depends on.</param>
        public void RegisterComponentDependencies(string componentName, IEnumerable<string> dependencies)
        {
            #region Tracing
            Trace.Verbose( "Registering Dependencies for Component '{0}'", componentName);
            #endregion

            DbUtil.ExecuteInTransaction(DbPlatform, ConnectionString,
                delegate(IDbTransaction transaction)
                    {
                        foreach(string dependency in dependencies)
                            DbManager.Execute(DbPlatform.ProviderFactory, transaction,
                                "insert into ComponentDependency (ComponentName, DependencyComponentName) values (:componentName, :dependencyComponentName);",
                                new string[] { "componentName", "dependencyComponentName" },
                                new object[] { componentName, dependency });
                    });

            #region Tracing
            Trace.Verbose( "Registered Dependencies for Component '{0}'", componentName);
            #endregion
        }

        /// <summary>
        /// Unregisters component <paramref name="componentName"/>.
        /// </summary>
        /// <param name="componentName"></param>
        public void UnregisterComponent(string componentName)
        {
            #region Tracing
            Trace.Verbose( "Unregistering Component '{0}'", componentName);
            #endregion

            DbUtil.ExecuteInTransaction(DbPlatform, ConnectionString,
                delegate(IDbTransaction transaction)
                    {
                        DbManager.Execute(DbPlatform.ProviderFactory, transaction,
                            "delete from Component where Name = :name;",
                            new string[] { "name" },
                            new object[] { componentName });
                    });

            #region Tracing
            Trace.Verbose( "Unregistered Component '{0}'", componentName);
            #endregion
        }

        /// <summary>
        /// Returns an instance of <see cref="ComponentReference"/> object
        /// which represents an installed component with name <paramref name="componentName"/>
        /// or <c>null</c> if no component with the given name is installed.
        /// </summary>
        /// <param name="componentName"></param>
        /// <returns></returns>
        public ComponentReference GetComponentReference(string componentName)
        {
            List<ComponentReference> components = new List<ComponentReference>();
            DbUtil.ExecuteInTransaction(DbPlatform, ConnectionString,
                delegate(IDbTransaction transaction)
                    {
                        components.AddRange(
                            DbManager.ExecuteDataReader(DbPlatform.ProviderFactory, transaction,
                                "select * from Component where Name = :componentName;",
                                new string[] { "componentName" },
                                new object[] { componentName  },
                                GetComponentReferenceMapper()));
                    });

            return components.Count == 0 ?
                null :
                components[0];
        }

        /// <summary>
        /// Returns an array of strings, which represent the names of components the <paramref name="componentName"/>
        /// depends on.
        /// </summary>
        /// <param name="componentName"></param>
        /// <returns></returns>
        public string[] GetComponentDependencies(string componentName)
        {
            List<string> dependencies = new List<string>();
            DbUtil.ExecuteInTransaction(DbPlatform, ConnectionString,
                delegate(IDbTransaction transaction)
                    {
                        dependencies.AddRange(
                            DbManager.ExecuteDataReader<string>(DbPlatform.ProviderFactory, transaction,
                                "select DependencyComponentName from ComponentDependency where ComponentName = :componentName order by DependencyComponentName;",
                                new string[] { "componentName" },
                                new object[] { componentName  },
                                delegate(IDataReader dr) { return dr.GetString(0); }));
                    });

            return dependencies.ToArray();
        }

        /// <summary>
        /// Returns an array of strings, which represent the names of components which depend on <paramref name="componentName"/>.
        /// </summary>
        /// <param name="componentName"></param>
        /// <returns></returns>
        public string[] GetComponentDependants(string componentName)
        {
            List<string> dependencies = new List<string>();
            DbUtil.ExecuteInTransaction(DbPlatform, ConnectionString,
                delegate(IDbTransaction transaction)
                    {
                        dependencies.AddRange(
                            DbManager.ExecuteDataReader<string>(DbPlatform.ProviderFactory, transaction,
                                "select ComponentName from ComponentDependency where DependencyComponentName = :componentName order by ComponentName;",
                                new string[] { "componentName" },
                                new object[] { componentName  },
                                delegate(IDataReader dr) { return dr.GetString(0); }));
                    });

            return dependencies.ToArray();
        }
        #endregion

        private IEnumerable<T> ExecuteDataReader<T>(string sqlStatement, Func<IDataReader, T> mapper)
        {
            List<T> mappedObjects = new List<T>();
            DbUtil.ExecuteInTransaction(DbPlatform, ConnectionString,
                delegate(IDbTransaction transaction)
                    {
                        mappedObjects.AddRange(
                            DbManager.ExecuteDataReader<T>(transaction, sqlStatement,
                                delegate(IDataReader reader)
                                    {
                                        return mapper(reader);
                                    }));
                    });

            return mappedObjects;
        }

        private static Func<IDataReader, ComponentReference> GetComponentReferenceMapper()
        {
            return delegate(IDataReader dataReader)
                {
                    return new ComponentReference(
                        (string)dataReader["Name"],
                        new Version((string)dataReader["Version"]),
                        new Uri((string)dataReader["Uri"]));
                };
        }
    }
}